%v1:
% function[comb,lower]=agent_ordering(grp,grpsize)%the grp the agent belongs
%    grpsizes=grpsize;
%    grpsizes(grp)=grpsizes(grp)-1;
%    ngrp=length(grpsize);
%    comb=[0:grpsizes(1)];
%    parfor g=2:ngrp
%        comb=combvec(comb,[0:grpsizes(g)]);
%    end
%    lower=grpsizes-comb;
% end

%v2:
% using sparse matrix: did not change much
% function[comb,lower]=agent_ordering(grp,grpsize)%the grp the agent belongs
%    grpsizes=grpsize;
%    grpsizes(grp)=grpsizes(grp)-1;
%    ngrp=length(grpsize);
%    comb=[0:grpsizes(1)];
%    parfor g=2:ngrp
%        comb=combvec(comb,[0:grpsizes(g)]);
%    end
%    lower=grpsizes-comb;
%    comb=sparse(comb);
%    lower=sparse(lower);
% end

%v3: use k, only take combinations where the agent has positive allocation
function[comb,lower,q_agent,numberpossibilities]=agent_ordering(grp,grpsize,grpk)%the grp the agent belongs
    grpsizes=grpsize;
    grpsizes(grp)=grpsizes(grp)-1;
    grpsizess=grpsizes;
    ngrp=length(grpsize);
    for g=1:ngrp
        grpsizes(g)=min(grpsizes(g),ceil(1./grpk(g)));
    end
    comb=[0:grpsizes(1)];
    for g=2:ngrp
        comb=combvec(comb,[0:grpsizes(g)]);
    end
    q_agent=comb'*grpk; 
    q_agent=min(1-q_agent,grpk(grp));
    q_agent=max(q_agent,0);
    lower=grpsizess-comb;
    comb=sparse(comb);
    lower=sparse(lower);
    comb(:,q_agent==0)=[];
    lower(:,q_agent==0)=[];
    q_agent(q_agent==0)=[];
     ncomb=size(comb,2);
    numberpossibilities=zeros(ncomb,1);
    for l=1:ncomb
          base=1;
          for g=1:ngrp
                base=base*nchoosek(grpsizess(g),comb(g,l));
          end
          numberpossibilities(l)=base;
    end
 end